from .handler import StarkHandler


class StarkSite(object):
    all_menu = {}

    def __init__(self):
        self._register_model = []
        self.app_name = 'stark'
        self.namespace = 'stark'

    def register_url(self, model_class, handler_class=None, prefix=None, pk_regx=None):
        """
        :param model_class: 模型类
        :param handler_class: 模型handler类
        :param prefix: 路由前缀
        :param pk_regx: 主键正则
        :return:
        """
        """
        {
            'model_class': model.User,
            'handler': StarkHandler(self, model_class, prefix, pk_regx),
        }
        """
        if handler_class:
            handler = handler_class(self, model_class, prefix, pk_regx)
        else:
            handler = StarkHandler(self, model_class, prefix, pk_regx)
        self._register_model.append({
            'model_class': model_class,
            'handler': handler
        })

    @property
    def urls(self):
        """
        获取路由列表
            [], app_name, namespace
        :return:
        """
        return self.get_urls(), self.app_name, self.namespace

    def get_urls(self):
        """
        为已注册的模型创建url
        :return:
        """
        patterns = []
        for item in self._register_model:
            handler = item['handler']
            urls = handler.get_urls()
            extra_urls = handler.extra_urls()
            patterns.extend(urls)
            patterns.extend(extra_urls)

            for item in urls:
                self.create_menu(handler, item)
        return patterns

    def create_menu(self, handler, item):
        """
        生成菜单
        :param handler:
        :param item:
        :return:
        """
        model_class_name = handler.model_class._meta.verbose_name
        list_name = handler.get_list_url_name
        add_name = handler.get_add_url_name
        # 列表与添加才有菜单
        if item.name in [list_name, add_name]:
            if not self.all_menu.get(model_class_name):
                self.all_menu[model_class_name] = []
            name = "列表" if item.name == list_name else "添加"
            self.all_menu[model_class_name].append({name: f'{self.app_name}:{item.name}'})


site = StarkSite()
